package com.beone.admin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.base.SuperServiceImpl;
import com.base.common.util.BaseStringUtils;
import com.beone.admin.entity.BasePermission;
import com.beone.admin.entity.BasePermissionRole;
import com.beone.admin.entity.BaseRole;
import com.beone.admin.entity.BaseUser;
import com.beone.admin.mapper.BaseRoleMapper;
import com.beone.admin.service.BasePermissionRoleService;
import com.beone.admin.service.BasePermissionService;
import com.beone.admin.service.BaseRoleService;
import com.beone.admin.service.BaseRoleUserService;
import com.beone.admin.utils.PaginationGatagridTable;
import com.beone.admin.utils.ServiceUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @Title 运维数据_角色信息 服务实现类
 * @Author 覃球球
 * @Version 1.0 on 2018-01-25
 * @Copyright 长笛龙吟
 */
@Service("BaseRoleService")
public class BaseRoleServiceImpl extends SuperServiceImpl<BaseRoleMapper, BaseRole> implements BaseRoleService {

    @Autowired
    private BasePermissionService permissionService;

    @Autowired
    private BasePermissionRoleService accessRoleService;
    @Autowired
    private BaseRoleUserService operationRoleUserService;

    /**
     * 获取所有可用的角色信息
     * @return
     */
    public List<BaseRole> getAllUsedRoles(){
        EntityWrapper<BaseRole> ew = new EntityWrapper<BaseRole>();
        ew.eq("is_use",1); // 1 表示可用角色
        return baseMapper.selectList(ew);
    }

    /**
     * 保存角色信息
     * @param role
     * @return
     */
    @Transactional
    public  boolean saveRole(BaseRole role){
        Integer result = 0;
        if(role.getRoleId() == null){
            role.setIsUse(1); //默认状态为启用
            result = baseMapper.insert(role);
        }else {
            result = baseMapper.updateById(role); //更新操作

            //删除角色与权限的关系
            accessRoleService.deleteAccessRoleByRoleId(role.getRoleId());
        }

        //保存角色与权限的关系
        String[] nodeIds = role.getPermissions().split(",");
        List<BasePermissionRole> accessRoles = new ArrayList<BasePermissionRole>();
        for(int i = 0; i < nodeIds.length; i++){
            BasePermissionRole oar = new BasePermissionRole();
            oar.setNodeId(Integer.valueOf(nodeIds[i]));
            oar.setRoleId(role.getRoleId());
            accessRoles.add(oar);
        }

        if(accessRoles.size() > 0){  //批量插入
            accessRoleService.insertBatchAccessRole(accessRoles);
        }

        if(result > 0){
            return true;
        }
        return false;
    }
    /**
     *删除角色信息
     * @author zero
     * @date 2018/4/9 17:01
     * @param roleId
     * @return boolean
     */
    @Transactional
    public  boolean delRole(Integer roleId){
        //删除角色与权限的关系
        Integer result=baseMapper. deleteById(roleId);
        accessRoleService.deleteAccessRoleByRoleId(roleId);
        operationRoleUserService.deleteRoleUserRelationByRoleId(roleId);
        if(result > 0){
            return true;
        }
        return false;
    }

    /**
     * 分页显示后台角色列表
     * @param role
     * @param currPage  当前页码
     * @param pageSize  每页显示记录数
     * @return
     */
     public PaginationGatagridTable getRolePagination(BaseRole role, int currPage, int pageSize){
         EntityWrapper<BaseRole> entityWrapper = new EntityWrapper<BaseRole>();

         if(StringUtils.isNotBlank(role.getRoleName())){ //拼接查询
             entityWrapper.like("role_name", BaseStringUtils.filterSpecSpecialValue(role.getRoleName()));
         }

         if(StringUtils.isNotBlank(role.getRoleDesc())){ //拼接查询
             entityWrapper.like("role_desc", BaseStringUtils.filterSpecSpecialValue(role.getRoleDesc()));
         }

         Page page = new Page<BaseUser>(currPage,pageSize);
         List<BaseRole> rows = baseMapper.selectPage(page, entityWrapper);
         return ServiceUtils.createGatagridTableJson(page,rows);
     }


    /**
     * 根据角色id查询对应权限
     * @param roleId 角色id
     * @return 格式化为easyui-tree适用的权限字符串
     */
    public Collection<BasePermission> showRolePermissionses(Integer roleId) {
        //根据角色Id，获取角色信息
        List<BasePermission> permissionsList = permissionService.getPermissionsesByRoleId(roleId);
        //获取easyui-tree json 格式
        return permissionService.getPermissionsTree(permissionsList,true); //获取当前角色下的所有权限资源
    }

    /**
     * 根据角色Id，选中属于该Id的所有权限
     * @param roleId
     * @return
     */
    public Collection<BasePermission> setOwnRolePermissions(Integer roleId){
        //根据角色Id，获取角色信息
        List<BasePermission> ownerPermissions = permissionService.getPermissionsesByRoleId(roleId);
        Collection<BasePermission> allPermission =
                permissionService.showPermissionMenuTree("all","used"); //显示全部可用权限

        if(ownerPermissions == null || ownerPermissions.size() == 0){
            return allPermission;
        }

        for (BasePermission permissions : allPermission) {
             setChecked(permissions, ownerPermissions);
        }
        return allPermission;
    }

    /**
     * 设置角色授权被选中的权限资源
     * @param permissions
     * @param rolePermissionList
     */
    private void setChecked(final BasePermission permissions, List<BasePermission> rolePermissionList) {
        if (null != permissions.getChildren()) {
            for (BasePermission per : permissions.getChildren()) {
                setChecked(per, rolePermissionList);
            }
        } else {
            for (BasePermission owner: rolePermissionList) {
                if(owner.getNodeId().equals(permissions.getNodeId())){
                    permissions.setChecked(true);
                    break;
                }
            }
        }
    }
}
